| Conditions | 4 |
| Total Lines | 23 |
| Code Lines | 18 |
| Lines | 0 |
| Ratio | 0 % |
| Tests | 16 |
| CRAP Score | 4 |
| Changes | 0 | ||
| 1 | 5 | import { MAX_LOOPS } from './config' |
|
| 3 | |||
| 4 | /** |
||
| 5 | * Find the rational number that best approximates the floating point number. |
||
| 6 | */ |
||
| 7 | 5 | export function rationalApproximation(n: number): Rat { |
|
| 8 | 8 | let m0 = 1n, |
|
| 9 | 8 | m1 = 0n, |
|
| 10 | 8 | m2 = 0n, |
|
| 11 | 8 | m3 = 1n |
|
| 12 | 8 | const r = new Rat(1n) |
|
| 13 | 8 | for (let i = 0; i < MAX_LOOPS; i++) { |
|
| 14 | 1485 | if (r.approximates(n)) break |
|
| 15 | 1478 | if (+r > n) { |
|
| 16 | 51 | m0 += m1 |
|
| 17 | 51 | m2 += m3 |
|
| 18 | } else { |
||
| 19 | 1427 | m1 += m0 |
|
| 20 | 1427 | m3 += m2 |
|
| 21 | } |
||
| 22 | 1478 | r.n = m0 + m1 |
|
| 23 | 1478 | r.d = m2 + m3 |
|
| 24 | } |
||
| 25 | 8 | return r |
|
| 26 | } |
||
| 70 |